package org.oos.atom.impl;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.oos.atom.OOSFeed;
import org.oos.atom.elements.Link;
import org.oos.atom.entries.OosEntry;

import com.google.api.client.util.Key;

abstract class AbstractFeedImpl<E extends OosEntry> implements OOSFeed<E> {

	private static final long serialVersionUID = 7459705520284046346L;

	@Key
	public String title;

	@Key
	public String id;

	@Key
	public String updated;

	@Key("link")
	public List<Link> links;

	@Key("os:itemsPerPage")
	public Integer itemsPerPage;

	@Key("os:totalResults")
	public Integer totalResults;

	@Key("os:startIndex")
	public Integer startIndex;

	@Override
	public Integer getItemsPerPage() {
		return itemsPerPage;
	}

	@Override
	public URL getNext() {
		Link nextLink = Link.find(links, "next").get(0);
		if (nextLink != null)
			try {
				return new URL(nextLink.getHref());
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		return null;

	}

	@Override
	public URL getPrevious() {
		Link nextLink = Link.find(links, "previous").get(0);
		if (nextLink != null)
			try {
				return new URL(nextLink.getHref());
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		return null;
	}

	@Override
	public Integer getStartIndex() {
		return startIndex;
	}

	@Override
	public String getTitle() {
		return title;
	}

	@Override
	public Integer getTotalResults() {
		if (totalResults != null) {
			return totalResults;
		} else {
			return 0;
		}
	}

	@Override
	public String getUpdated() {
		return updated;
	}

	@Override
	public URL getUrl() {
		try {
			return new URL(id);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public AbstractFeedImpl<E> clone() throws CloneNotSupportedException {
		return (AbstractFeedImpl<E>) super.clone();
	}

}
